package servlets;

import ru.ipo.dces.clientservercommunication.AcceptedResponse;
import ru.ipo.dces.clientservercommunication.CheckSolutionRequest;
import ru.ipo.dces.clientservercommunication.CheckerRequest;
import ru.ipo.dces.clientservercommunication.RequestFailedResponse;
import ru.ipo.dces.server.http.PHP;
import utils.LoggerFactory;
import utils.ReadWriteObject;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.logging.Logger;

public class CheckSolutionServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        Logger logger = LoggerFactory.getLoggerForServlet(this);

        OutputStream out = response.getOutputStream();
        InputStream is = request.getInputStream();

        try {
            CheckSolutionRequest unserializedReq = ReadWriteObject.readRequest(CheckSolutionRequest.class, is);
            ReadWriteObject.writeResponse(new AcceptedResponse(), out);
            out.flush();

            CheckerRequest checkerRequest = new CheckerRequest();
            checkerRequest.result = unserializedReq.userAnswer;
            checkerRequest.sessionID = "admin_session";
            checkerRequest.submissionID = unserializedReq.submissionID;


        } catch (Exception e) {
            logger.info(e.getMessage());
            RequestFailedResponse failedResponse = new RequestFailedResponse();
            failedResponse.failReason = RequestFailedResponse.FailReason.BrokenServerError;
            failedResponse.extendedInfo = e.getMessage();
            try {
                PHP.serialize(failedResponse, out);
            } catch (IllegalAccessException ignored) {
                logger.info(ignored.getMessage());
            }
            out.flush();
        }
    }
}
